//
//  STCommodityAllViewModel.swift
//  StarTimesON
//
//  Created by Toj on 8/19/22.
//  Copyright © 2022 StarTimes. All rights reserved.
//

import UIKit

typealias MobileProductRequestCompletion = ((_ product: MemberProductDto) -> Void)
typealias AllProductRequestCompletion = ((_ sections: [STCommodityAllSectionModel]) -> Void)

class STCommodityAllViewModel: NSObject {
    
    let ds_categroy = "STAllCommodityController"
    
    private(set) var dataBundleInfo: DataBundleInfo?
    
    // 全部商品
    private(set) var products: [String: MemberProductDto] = [:]
    private var sections: [STCommodityAllSectionModel] = []
    // 优先级最高的商品
    private var maxLevelProduct = MemberProductDto()
    
    private func responseAllCommodityDetail(memberCategoryDto: [MemberCategoryDto],
                                           dataBundleInfo: DataBundleInfo?) {
        // 全部商品
        responseMemberCategoryDto(memberCategoryDto)
        
        let country = STUserModel.shared.areaDtoInfo?.country ?? "NONE"
        let isCountry = AppFunctionManager.TVOpenCountry[country] ?? ""
        var isOpenDVBService = isCountry == "1"
        if !isOpenDVBService {
            isOpenDVBService = AppFunctionManager.isUsable(function: .FB_SELFSERVICE)
        }
        if isOpenDVBService {
            // TV
            responseTVInfo()
        }
        
        // 流量包
        responseBundleInfo(dataBundleInfo)
    }
    
    // 商品数据
    private func responseMemberCategoryDto(_ categories: [MemberCategoryDto]) {
        // 清空数据
        sections.removeAll()
        products.removeAll()
        maxLevelProduct = MemberProductDto()
        // 捆绑包
        var freeProduces: [MemberProductDto] = []
        // 独立会员包
        var saveProduces: [MemberProductDto] = []
        
        categories.forEach { category in
            category.products.forEach { product in
                // 未知 商品过滤
                if product.product_type == .unknown { return }
                
                // 顺便找到优先级最高的商品
                if product.level > maxLevelProduct.level
                { maxLevelProduct = product }
                
                // 全部商品
                let productID = String(product.id)
                products[productID] = product
                
                // 捆绑包
                if product.product_type == .dataFree {
                    freeProduces.append(product)
                    return
                }
                // 独立会员包
                if product.product_type == .dataSave {
                    saveProduces.append(product)
                    return
                }
            }
        }
        
        // 独立会员包组
        if !saveProduces.isEmpty {
            let saveSection = STCommodityAllSectionModel()
            saveSection.isImage = false
            saveSection.title = OLLocalize("membership_video")
            saveSection.products = saveProduces
            saveSection.type = .saveProduces
            sections.append(saveSection)
        }
        
        // 捆绑包组
        if !freeProduces.isEmpty {
            let freeSection = STCommodityAllSectionModel()
            freeSection.isImage = false
            freeSection.title = OLLocalize("membership_videoplusdata")
            freeSection.products = freeProduces
            freeSection.type = .freeProduces
            sections.append(freeSection)
        }
    }
    
    // 流量包 组
    private func responseBundleInfo(_ dataBundleInfo: DataBundleInfo?) {
        self.dataBundleInfo = dataBundleInfo
        guard let bundleInfo = dataBundleInfo else { return }
        guard !bundleInfo.carrier_name.isEmpty else { return }
        
        let bundleProduct = MemberProductDto()
        bundleProduct.product_logo = bundleInfo.icon
        bundleProduct.name = bundleInfo.description
        bundleProduct.id = bundleInfo.carrierId
        bundleProduct.link = bundleInfo.link
        
        let bundleSection = STCommodityAllSectionModel()
        bundleSection.isImage = false
        bundleSection.title = "membership_DataBundle".localized()
        bundleSection.products = [bundleProduct]
        bundleSection.type = .bundleProduce
        sections.append(bundleSection)
    }
    
    // DVB TV 组
    private func responseTVInfo() {
        let tvSection = STCommodityAllSectionModel()
        tvSection.isImage = false
        tvSection.type = .tv
        tvSection.title = "membership_TV".localized()
        sections.append(tvSection)
    }
    
    private func requestFitProduct(pid: String, completion: ((_ isSuccess: Bool, _ product: MemberProductDto?) -> Void)? = nil) {
        // 判断商品是否存在
        // 如果商品存在, 获取优先级最高的商品
        // 查看当前商品 是否 在所有商品里
        let product = products[pid] ?? maxLevelProduct
        let isSuccess = product.id > 0
        completion?(isSuccess, product)
        mobileProductRequest?(product)
        allProductRequest?(sections)
    }
    
    private var isLoading = false
    
    private let fprovider = STNetwork<MemberApi>()
    
    private var currentProduct: MemberProductDto?
    // 请求所有筛选最有的回调
    var mobileProductRequest: MobileProductRequestCompletion?
    // 点击某个商品回调
    var didTapProductHandle: MobileProductRequestCompletion?
    // 所有商品获取后回调
    var allProductRequest: AllProductRequestCompletion?
    // 获取所有商品中的回调
    var requestAllProductsLoading: (()->Void)?
}

// MARK: - 数据请求
extension STCommodityAllViewModel {
    
    // 给All 调用
    public func requestAllProducts(completion: AllProductRequestCompletion? = nil) {
        if !sections.isEmpty {
            completion?(sections)
            return
        }
        requestAllCommodityDetail { [weak self] _, _ in
            guard let weakself = self else { return }
            completion?(weakself.sections)
        }
    }
    
    // 给Mobile 调用
    // 获取所有商品列表 和 流量包
    public func requestAllCommodityDetail(product id: String = "", _ completion: ((_ isSuccess: Bool, _ product: MemberProductDto?) -> Void)? = nil) {
        requestAllProductsLoading?()
        if isLoading { return }
        isLoading = true
       
        fprovider.sendBatchResultObjectRequest(MemberApi.getAllProduct, target2: MemberApi.getBoundleOfRecommend) { [weak self] (result: STResult<(MemberProductResponse, DataBundleResult), MoyaError>) in
            guard let strongSelf = self else { return }
            
            switch result {
            case .success(let value):
                // 数据
                let (productsResult, bundleResult) = value
                // 所有商品
                strongSelf.responseAllCommodityDetail(memberCategoryDto: productsResult.data, dataBundleInfo: bundleResult.data)
                strongSelf.isLoading = false
                strongSelf.requestFitProduct(pid: id, completion: completion)
            case .failure(_):
                strongSelf.isLoading = false
                completion?(false, nil)
            }
        }
    }
    
    // 获取联盟指定商品
    func requestProductOfUTM(utm: String, product id: String, _ completion: ((_ isSuccess: Bool, _ product: MemberProductDto?)->Void)? = nil) {
        if isLoading { return }
        isLoading = true
        
        print("-->toj: utm: \(utm) id:\(id )")
        
        var ext: [String: Any] = [:]
        ext[DSKExtension.product_id.rawValue] = id
        ext[DSKExtension.referrer.rawValue] = utm
        DataStatistics.shared.union(action: .product_request, ext: ext)
        
        fprovider.sendRequest(MemberApi.getProductInfo(utm: utm, id: id)) { [weak self] (result: STResult<(MemberProductResponse), MoyaError>) in
            guard let strongSelf = self else { return }
            
            switch result {
            case .success(let value):
                ext[DSKExtension.error_msg.rawValue] = value.message
                ext[DSKExtension.error_code.rawValue] = "\(value.code)"
                // 国家不一致
                if value.code == 101 {
                    UIViewController.topMost?.view.showToast(message: "union_errormask_locationchanged".localized(),delayTime: 4, enabled: true)
                    break
                }
                // 后端状态码 非0: 失败
                guard value.code == 0 else { break }
                // 数据为空
                let categories = value.data
                guard !categories.isEmpty else {
                    ext[DSKExtension.error_msg.rawValue] = "not_data"
                    break
                }
               
                // 所有商品
                strongSelf.responseAllCommodityDetail(memberCategoryDto: categories, dataBundleInfo: nil)
                strongSelf.isLoading = false
                // 找到优先级最高的商品请求详情
                strongSelf.requestFitProduct(pid: id, completion: completion)
               
                DataStatistics.shared.union(action: .product_result, label: "success")
                
                return
            case .failure(let error):
                let err = error as NSError
                ext[DSKExtension.code.rawValue] = "\(err.code)"
                ext[DSKExtension.msg.rawValue] = "\(err.localizedDescription)"
            }
            
            strongSelf.isLoading = false
            completion?(false, nil)
            strongSelf.requestAllCommodityDetail(product: id, nil)
            DataStatistics.shared.union(action: .product_result, label: "fail", ext: ext)
        }
    }
    
    /// 取消全部请求
    func cancelAllRequest() {
        fprovider.cancelAll()
    }
}

extension STCommodityAllViewModel {
    
    // 选择商品 - OTT
    func ds_didTapProduct(product: MemberProductDto) {
        let event = DSEvent(category: ds_categroy, action: "ProdTap", label: product.name, value: "1")
        DataStatistics.sendEvent(event: event, msg: product.dataStatistics)
    }
    
    // 选择商品 - 数据包
    func ds_didTapDataBundleInfo(id: String) {
        let event = DSEvent(category: ds_categroy, action: "dataplan_product_click", label: "", value: "1", lt: .event)
        DataStatistics.sendEvent(event: event, msg: ["dataplan_id": id])
    }
}
